//
//  ZNBDismissAnimator.m
//  ZNB
//
//  Created by znb_iOS on 16/7/28.
//  Copyright © 2016年 znb. All rights reserved.
//

#import "ZNBDismissAnimator.h"

@implementation ZNBDismissAnimator

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.5;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    CGRect initalFrame = [transitionContext initialFrameForViewController:fromVC];
    CGRect finalFrame = CGRectOffset(initalFrame, initalFrame.size.width, 0);
    UIView *containerView = [transitionContext containerView];
    UIView *coverView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    coverView.backgroundColor = [UIColor blackColor];
    coverView.alpha = 0.3f;
    if ([transitionContext isInteractive])
    {
//        [toVC.view addSubview:coverView];
//        toVC.view.transform = CGAffineTransformMakeScale(0.95, 0.95);
//        toVC.view.transform = CGAffineTransformMakeTranslation(-100, 0);
    }
    else
    {
        toVC.view.transform = CGAffineTransformMakeTranslation(-100, 0);
    }
    
    [containerView insertSubview:toVC.view belowSubview:fromVC.view];
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        fromVC.view.frame = finalFrame;
        if ([transitionContext isInteractive])
        {
//            coverView.alpha = 0;
//            toVC.view.transform = CGAffineTransformMakeScale(1, 1);
            fromVC.view.transform = CGAffineTransformMakeTranslation(0, 0);
        }
        else
        {
            toVC.view.transform = CGAffineTransformMakeTranslation(0, 0);
        }
        
    } completion:^(BOOL finished) {
//        [coverView removeFromSuperview];
//        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
//        [fromVC.view removeFromSuperview];
        
        if ([transitionContext transitionWasCancelled])
        {
            [toVC.view removeFromSuperview];
        } else {
            [fromVC.view removeFromSuperview];
        }
        // inform the context of completion
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
    
}
@end
